<template>
  <div style="width: 90%; margin: 0 auto">
    <!-- 查询框 -->
    <el-row style="margin-left: -55px">
      <el-col :span="20">
        <el-input
          placeholder="请输入内容"
          v-model="select_value"
          style="background-color: #fff; width: 60%"
        >
          <el-select
            v-model="select_key"
            slot="prepend"
            placeholder="查询类型"
            style="width: 130px"
          >
            <el-option label="编码" value="role_num"></el-option>
            <el-option label="名称" value="role_name"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="loadRoles()"
            >查询</el-button
          >
        </el-input>
        <el-button
          style="vertical-align: middle; margin-left: 20px"
          type="success"
          icon="el-icon-plus"
          @click="addOneRole()"
          >添加</el-button
        >
        <el-button
          style="vertical-align: middle; margin-left: 20px"
          icon="el-icon-delete"
          type="danger"
          @click="delAllRoles()"
          >批量删除</el-button
        >
      </el-col>
    </el-row>

    <!-- 角色/职位列表 -->
    <el-row style="margin-top: 15px">
      <el-card shadow="hover">
        <!-- 卡片头部 -->
        <div slot="header" class="clearfix">
          <el-row style="height: 40px">
            <el-col :span="24">
              <div
                style="
                  width: 100%;
                  font-size: 20px;
                  text-align: center;
                  color: #000000;
                  margin: 10px 0px 0px 10px;
                "
              >
                职位全览
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 列表 -->
        <el-table
          ref="roleListTable"
          :data="roleList"
          highlight-current-row
          stripe
          border
          @current-change="handleCurrentChange"
          @selection-change="handleSelectionChange"
          style="width:540px; margin: 0 auto"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            property="role_id"
          >
          </el-table-column>
          <el-table-column
            property="role_num"
            label="职位编码"
            align="center"
            width="85"
          ></el-table-column>
          <el-table-column
            property="role_name"
            label="职位名称"
            align="center"
            width="100"
          ></el-table-column>

          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button
                type="success"
                @click="updateRole(scope.row)"
                icon="el-icon-edit"
                size="small"
                circle=""
                ></el-button
              >
              <el-button
                type="danger"
                @click="deleteRole(scope.row)"
                icon="el-icon-delete"
                size="small"
                circle=""
                ></el-button
              >
              <el-button
                type="warning"
                @click="givePers(scope.row)"
                icon="el-icon-edit"
                size="small"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>

    <!-- 添加职位弹出框 -->
    <el-dialog :visible.sync="addRoleDialogVisible" title="添加新职位">
      <!-- 添加表单 -->
      <el-form
        :model="addRole"
        :rules="rules"
        ref="addRoleDialog"
        label-width="100px"
      >
        <el-form-item label="职位编码" prop="role_num">
          <el-input type="text" v-model="addRole.role_num"></el-input>
        </el-form-item>
        <el-form-item label="职位名称" prop="role_name">
          <el-input type="text" v-model="addRole.role_name"></el-input>
        </el-form-item>

        <!-- 提交表单按钮 -->
        <el-form-item>
          <el-row id="centerBtnAdd">
            <el-button type="success" @click="saveRole('addRoleDialog')"
              >保存</el-button
            >
            <el-button type="primary" @click="resetAddRole('addRoleDialog')"
              >重置</el-button
            >
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加职位弹出框结束-->

    <!-- 修改职位弹出框 -->
    <el-dialog :visible.sync="updRoleDialogVisible" title="修改职位">
      <!-- 添加表单 -->
      <el-form
        :model="updRole"
        :rules="rules"
        ref="updRoleDialog"
        label-width="100px"
      >
        <el-form-item label="职位编码" prop="role_num">
          <el-input type="text" v-model="updRole.role_num"></el-input>
        </el-form-item>
        <el-form-item label="职位名称" prop="role_name">
          <el-input type="text" v-model="updRole.role_name"></el-input>
        </el-form-item>

        <!-- 提交表单按钮 -->
        <el-form-item>
          <el-row id="centerBtnAdd">
            <el-button type="success" @click="saveUpdRole('updRoleDialog')"
              >保存</el-button
            >
            <el-button type="primary" @click="resetUpdRole('updRoleDialog')"
              >重置</el-button
            >
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改职位弹出框结束-->

    <!-- 分配权限对话框打开 -->
    <el-dialog
      title="分配权限"
      :visible.sync="persDialogVisible"
      width="30%"
      center
    >
      <!-- 树形控件 -->
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
      >
      </el-tree>
      <!-- 树形控件结束 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savePers()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框关闭 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 查询类型和值
      select_value: "",
      select_key: "",

      //职位结果集
      roleList: [],

      //当前行
      currentRow: "",

      //多选框选中行id
      multipleSelection: [],

      //新添职位对话框显示属性
      addRoleDialogVisible: false,

      //新添职位数据
      addRole: {
        role_num: "",
        role_name: "",
      },

      //修改职位对话框显示属性
      updRoleDialogVisible: false,

      //修改职位数据
      updRole: {
        role_num: "",
        role_name: "",
      },

      //分配对话框显示属性
      persDialogVisible: false,
      //被选中待分配权限的的role_id
      selectedRid: "",

      //树形控件上挂载的数据
      treeData: [],
      //默认选中的persid
      checkedNodes: [],
      //默认数据属性
      defaultProps: {
        children: "children",
        label: "label",
      },

      //表单验证规则
      rules: {
        role_num: [
          { required: true, message: "请填写职位编码", trigger: "blur" },
          { max: 5, message: "编码最多5位", trigger: "blur" },
        ],
        role_name: [
          { required: true, message: "请填写职位名称", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5]{2,50}$/,
            message: "职位名称为2～50个汉字，不能有字母、数字、特殊字符或空格",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //加载所有角色
    loadRoles() {
      if (this.select_key == "" && this.select_value != "") {
        this.$message({
          type: "warning",
          message: "请选择查询类型!",
        });
      } else {
        this.$axios
          .get("/roles/key", {
            params: {
              key: this.select_key,
              value: this.select_value,
            },
          })
          .then((resp) => {
            if (resp.data.status == 1000) {
              this.roleList = resp.data.data;
              // alert(this.userList)
            } else {
              this.$message({
                type: "error",
                message: "暂无相应数据!",
              });
            }
          })
          .catch((error) => {});
      }
    },

    // 表格控制当前选中行
    handleCurrentChange(val) {
      this.currentRow = val;
    },

    //表格中已选中的多选框
    handleSelectionChange(val) {
      let ids = [];
      for (let role of val) {
        ids.push(role.role_id);
      }
      this.multipleSelection = ids;
    },

    //添加职位/角色
    addOneRole() {
      this.addRoleDialogVisible = true;
    },

    //保存新添职位/角色
    saveRole(addRoleDialog) {
      // console.log(this.addUser);

      this.$refs[addRoleDialog].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/roles", this.addRole)
            .then((resp) => {
              if (resp.data.status == 1000) {
                //alert(resp.data.message);
                this.$message({
                  type: "success",
                  message: "保存成功!",
                });
                this.addRoleDialogVisible = false;
                this.$refs[addRoleDialog].resetFields();
                this.loadRoles();
              } else if (resp.data.status == 1001) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!",
                });
              } else if (resp.data.status == 1002) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!职位编码不能重复!",
                });
              }
            })
            .catch((error) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //重置新添职位
    resetAddRole(addRoleDialog) {
      this.$refs[addRoleDialog].resetFields();
    },

    //点击编辑职位按钮
    updateRole(role) {
      //console.log(user.user_id);
      this.$axios
        .get("/roles/" + role.role_id)
        .then((resp) => {
          if (resp.data.status == 1000) {
            this.updRole = resp.data.data;
          } else {
            console.log("修改时查询修改职位失败");
          }
        })
        .catch((error) => {});
      this.updRoleDialogVisible = true;
    },

    //保存修改职位
    saveUpdRole(updRoleDialog) {
      //console.log(this.updUser);
      this.$refs[updRoleDialog].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/roles", this.updRole)
            .then((resp) => {
              if (resp.data.status == 1000) {
                //alert(resp.data.message);
                this.$message({
                  type: "success",
                  message: "保存成功!",
                });
                this.updRoleDialogVisible = false;
                this.$refs[updRoleDialog].resetFields();
                this.loadRoles();
              } else if (resp.data.status == 1001) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!",
                });
              } else if (resp.data.status == 1002) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "保存失败!职位编码不能重复!",
                });
              }
            })
            .catch((error) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //重置修改职位
    resetUpdRole(updRoleDialog) {
      //alert("######");
      this.updateRole(this.updRole);
    },

    //删除职位
    deleteRole(role) {
      this.$confirm("确定删除该职位吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete("/roles/" + role.role_id)
            .then((resp) => {
              if ((resp.data.status = 1000)) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.loadRoles();
              } else if (resp.data.status == 1001) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              } else if (resp.data.status == 1002) {
                //alert(resp.data.message);
                this.$message({
                  type: "error",
                  message: "删除失败！这个职位有人正在使用,无法删除!",
                });
              }
            })
            .catch((error) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //批量删除
    delAllRoles() {
      //alert(this.multipleSelection)
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请至少选择一项",
          type: "warning",
        });
      } else {
        this.$confirm("此操作将永久删除该职位, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .post("/roles/deletelist", this.multipleSelection)
              .then((resp) => {
                if (resp.data.status == 1000) {
                  this.$message({
                    message: "批量删除成功",
                    type: "success",
                  });
                  this.loadRoles();
                } else if (resp.data.status == 1001) {
                  //alert(resp.data.message);
                  this.$message({
                    type: "error",
                    message: "批量删除失败!",
                  });
                } else if (resp.data.status == 1002) {
                  //alert(resp.data.message);
                  this.$message({
                    type: "error",
                    message: "删除失败！这个职位有人正在使用,无法批量删除!",
                  });
                }
              })
              .catch((error) => {});
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },

    //点击分配权限
    givePers(role) {
      //获取我们需要的树状控件上需要挂载的数据
      /*
            数据分为两部分：
            1、所有的权限的信息（再服务器端已经转换为符合树状控件的数据格式了）
            2、该角色id对应的所有的权限id
            */
      this.persDialogVisible = true;
      this.selectedRid = role.role_id;
      this.$axios
        .get("/perstree/" + this.selectedRid)
        .then((res) => {
          //将树上挂的数据设置到数据模型的data属性中
          this.treeData = res.data.data.treeNodes;
          //将角色对应的所有权限id设置到数据模型中的checkedNodes中
          this.checkedNodes = res.data.data.persIds;

          //设置默认选中项
          setTimeout(() => {
            //设置默认选中项
            this.loadchecked();
          }, 500);
        })
        .catch((error) => {});
      //console.log(this.checkedNodes);
    },
    //设置默认选中项
    loadchecked() {
      //nconsole.log(this.checkedNodes);
      //checkedNodes:角色对应的权限id
      for (var cid of this.checkedNodes) {
        //根据key(id)获得树上的每一个节点,记得树上要设置node-key
        var treeNode = this.$refs.tree.getNode(cid);

        //判断树的节点如果是叶子节点
        if (treeNode.isLeaf) {
          // console.log(cid);
          //选中节点
          this.$refs.tree.setChecked(treeNode, true);
        }
      }
    },

    //保存权限
    savePers() {
      //获得选中的树节点的id
      var ids = this.$refs.tree.getCheckedKeys();
      //获得半选中状态的树节点的id
      var halfIds = this.$refs.tree.getHalfCheckedKeys();
      //将两个数组中的元素连接起来，放到一个数组中
      ids = [...ids, ...halfIds];
      console.log(ids);

      //角色id，所有选中的权限id
      this.$axios
        .post("/pers/role", {
          role_id: this.selectedRid,
          perIds: ids,
        })
        .then((res) => {
          if (res.data.status == 1000) {
            this.persDialogVisible = false;
            //清空默认节点
            this.resultNodes = [];
            this.$message({
              message: "分配成功",
              type: "success",
            });
          } else {
            this.$message({
              message: "分配失败",
              type: "error",
            });
          }
        })
        .catch((error) => {});
    },
  },

  mounted() {
    this.loadRoles();
  },
};
</script>
<style >
.el-dialog {
  width: 35%;
}
.el-form-item__content {
  text-align: left;
}

#centerBtnAdd,
#centerBtnUpd {
  margin-left: 75px;
}
</style>